import 'dart:io';
import 'dart:typed_data';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_hms_scan/model/scan_bean.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:r_upgrade/r_upgrade.dart';
import 'package:tencent_kit/tencent_kit.dart';
import 'package:x_common_utils/cache_encryption_decrypt_util/cache_encryption_decrypt_util.dart';
import 'package:xinxuan/common/dialogs/activity_dialog.dart';
import 'package:xinxuan/common/dialogs/upload_apk_dialog.dart';
import 'package:xinxuan/common/notice_dialog.dart';
import 'package:xinxuan/config/app_config.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/router/app_routers.dart';
import 'package:xinxuan/utils/cache_key_util.dart';
import 'package:xinxuan/utils/color_util.dart';
import 'package:xinxuan/utils/dialog_queue_manager_util.dart';
import 'package:xinxuan/vo/announcements_vo.dart';
import 'package:xinxuan/vo/user_data_vo.dart';
import 'package:xinxuan/vo/version_vo.dart';
import 'dart:ui' as ui;
import 'package:permission_handler/permission_handler.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:flutter_hms_scan/flutter_hms_scan.dart';

class CommonPageController extends GetxController {

  // final ScanBean _bean = ScanBean();
  
  /// 版本
  var appVersion = ''.obs;
  /// 设备 IOS、Android
  var appDeviceType = ''.obs;
  /// 是否为审核版本
  var isRevirew = false.obs;
  /// tabIndex
  var tabIndex = 0.obs;
  /// 是否已登录
  var isAuthenticated = false.obs;
  /// 用户信息
  var userData = UserData(
    nickname: '', 
    avatar: '', 
    levelStr: '', 
    invitationCode: '', 
    invitationUrl: '',
    isTeamLeader: 0,
    teamId: 0,
    isNew: 0,
    isActivity: 0,
    newUsers: 0,
    expectedSubsidy: '0.00',
    actualSubsidy: '0.00',
    isAdmin: 0,
    isWriteoffOfficer: 0,
    isPayPassword: 0,
    assets: AssetsData(
      shopping: '0.00',
      subsidy: '0.00',
      cash: '0.00',
      gratitude: '0.00',
      feedbackGratitude: '0.00'
    ),
    statistics: Statistics(
      seckill: [0, 0, 0, 0, 0],
      shopping: [0, 0, 0]
    )
  ).obs;
  /// 用户昵称
  String nickname = '';
  /// 微信号
  String wechat = '';
  /// 真实姓名
  String realname = '';
  /// 身份证号码
  String number = '';
  /// 安装包下载信息
  DownloadInfo? downloadInfo;
  /// 最新版本信息
  var versionData = VersionData().obs;

  @override
  void onInit() {
    print('common_page_controller..........');
    downloadListen();
    EasyLoading.instance
      ..displayDuration = const Duration(milliseconds: 2000)
      ..indicatorType = EasyLoadingIndicatorType.fadingCircle
      ..toastPosition = EasyLoadingToastPosition.center
      ..loadingStyle = EasyLoadingStyle.custom
      ..radius = 5
      ..backgroundColor = bgBlackColor_50
      ..boxShadow = <BoxShadow>[]
      ..indicatorColor = bgWhiteColor
      ..textColor = textWhiteColor
      ..maskColor = bgBlackColor_50
      ..progressColor = bgBlackColor_50
      ..userInteractions = true
      ..successWidget = Image.asset(
        'assets/icons/icon_success.png',
        width: 28,
        height: 28
      )..dismissOnTap = false;
    super.onInit();
  }
  
  /// 检查用户是否登录
  Future<bool> checkLogin({bool loading = true}) async {
    // String _token = await CacheEncryptionDecryptUtil.getStringCacheEncryption(key: CacheKeyUtil.token);
    isAuthenticated.value = !TextUtil.isEmpty(AppConfig.token);
    if (!isAuthenticated.value) {
      userData.value = UserData(
        nickname: '', 
        avatar: '', 
        levelStr: '', 
        invitationCode: '', 
        invitationUrl: '',
        isTeamLeader: 0,
        teamId: 0,
        isNew: 0,
        isActivity: 0,
        newUsers: 0,
        expectedSubsidy: '0.00',
        actualSubsidy: '0.00',
        isAdmin: 0,
        isWriteoffOfficer: 0,
        isPayPassword: 0,
        assets: AssetsData(
          shopping: '0.00',
          subsidy: '0.00',
          cash: '0.00',
          gratitude: '0.00',
          feedbackGratitude: '0.00'
        ),
        statistics: Statistics(
          seckill: [0, 0, 0, 0, 0],
          shopping: [0, 0, 0]
        )
      );
      showNoticeDialog();
      update();
      return false;
    }
    getUserInfo(loading: loading);
    return isAuthenticated.value;
  }

  /// 获取用户信息
  getUserInfo({bool loading = true}) async {
    UserDataVo userDataVo = await HttpUtilService.getUserInfo(loading: loading);
    userData.value = userDataVo.data!;
    // userData.value.newUsers = 0;
    showNoticeDialog();
    update();
  }

  /// 修改昵称
  editUserName() async {
    if (TextUtil.isEmpty(nickname)) {
      nickname = '${userData.value.nickname}';
    }
    Map<String, dynamic> param = {
      'nickname': nickname
    };
    UserDataVo userDataVo = await HttpUtilService.editUser(param: param);
    userData.value = userDataVo.data!;
    Get.back();
    getUserInfo();
  }
  
  /// 修改微信号
  editUserWechat() async {
    if (TextUtil.isEmpty(wechat)) {
      EasyLoading.showToast('请输入微信号');
      return;
    }
    Map<String, dynamic> param = {
      'wechat': wechat
    };
    UserDataVo userDataVo = await HttpUtilService.editUser(param: param);
    userData.value = userDataVo.data!;
    Get.back();
    getUserInfo();
  }

  /// 检查版本信息
  checkAppVersion({bool showLoading = true}) async {
    VersionVo versionVo = await getVersionMsg();
    versionData.value = versionVo.data!;
    // versionVo.data!.isUpdate = 1;
    // versionVo.data!.forcedUpdate = 0;
    if (versionVo.data!.isUpdate == 1) {
      // 入队
      DialogQueueManager.enqueue(() {
        Get.dialog(
          UploadApkDialog(
            versionVo.data!.downloadUrl!, 
            versionVo.data!.content!,
            versionVo.data!.version!, 
            versionVo.data!.forcedUpdate!
          ),
          barrierDismissible: false,
        );
      });
      // Get.dialog(
      //   UploadApkDialog(
      //     versionVo.data!.downloadUrl!, 
      //     versionVo.data!.content!,
      //     versionVo.data!.version!, 
      //     versionVo.data!.forcedUpdate!
      //   ),
      //   barrierDismissible: false,
      // );
    } else {
      if (showLoading) {
        EasyLoading.showToast('已经是最新版本');
      }
    }
  }

  /// 获取最新版本信息
  Future<VersionVo> getVersionMsg() async {
    VersionVo versionVo = await HttpUtilService.checkVersion();
    // versionVo.data!.isReview = 1;
    isRevirew.value = versionVo.data!.isReview == 1;
    return versionVo;
  }

  /// 同意授权
  consentAuthorization() async {
    // await getVersionMsg();
    // CacheEncryptionDecryptUtil.saveBoolCacheEncryption(key: CacheKeyUtil.showUserAgreement, value: true);
    // if (isRevirew.value) {
    //   Get.offAllNamed(AppRouters.REVIEW_COMMON_PAGE);
    // } else {
    //   Get.offAllNamed(AppRouters.COMMON_PAGE);
    // }
    Get.offAllNamed(AppRouters.COMMON_PAGE);
    checkAppVersion(showLoading: false);
    checkLogin();
    CacheEncryptionDecryptUtil.saveBoolCacheEncryption(key: CacheKeyUtil.showUserAgreement, value: true);
  }

  /**
   * 
   * 
   * EasyLoading.instance.userInteractions = true;
   * if (showLoading) {
        EasyLoading.instance.userInteractions = false;
      EasyLoading.show();
      }
   * 
   */
  
  /// 下载并安装Apk
  downloadApk(String apkUrl, String versionName, { bool showLoading = false}) async {
    if (showLoading) {
      EasyLoading.instance.userInteractions = false;
      EasyLoading.show();
    }
    if (downloadInfo == null) {
      showToast('后台下载中');
      await RUpgrade.upgrade(
        apkUrl,
        fileName: '魔法星选',
        notificationStyle: NotificationStyle.planTimeAndSpeech
      );
    } else {
      if (downloadInfo!.status == DownloadStatus.STATUS_PAUSED) {
        RUpgrade.upgradeWithId(downloadInfo!.id!);
        showToast('已继续下载');
      }
      if (downloadInfo!.status == DownloadStatus.STATUS_PENDING) {
        RUpgrade.cancel(downloadInfo!.id!);
        downloadInfo = null;
        downloadApk(apkUrl, versionName);
      }
      if (downloadInfo!.status == DownloadStatus.STATUS_RUNNING) {
        showToast('后台下载中');
      }
      if (downloadInfo!.status == DownloadStatus.STATUS_SUCCESSFUL) {
        // showToast('下载成功');
        if (EasyLoading.isShow) {
          EasyLoading.instance.userInteractions = true;
          EasyLoading.dismiss();
        }
        RUpgrade.install(downloadInfo!.id!);
      }
      if (downloadInfo!.status == DownloadStatus.STATUS_FAILED) {
        showToast('下载失败，将重新下载');
        RUpgrade.cancel(downloadInfo!.id!);
        downloadInfo = null;
        downloadApk(apkUrl, versionName);
      }
      if (downloadInfo!.status == DownloadStatus.STATUS_CANCEL) {
        showToast('下载取消，将重新下载');
        RUpgrade.cancel(downloadInfo!.id!);
        downloadInfo = null;
        downloadApk(apkUrl, versionName);
      }
    }
  }

  /// 监听下载进度
  downloadListen() {
    if (Platform.isAndroid) {
      RUpgrade.stream.listen((DownloadInfo info) async {
        if (info.status == DownloadStatus.STATUS_CANCEL || 
            info.status == DownloadStatus.STATUS_FAILED ||
            info.status == DownloadStatus.STATUS_PAUSED ||
            info.status == DownloadStatus.STATUS_PENDING ||
            info.status == DownloadStatus.STATUS_SUCCESSFUL) {
          if (EasyLoading.isShow) {
            EasyLoading.instance.userInteractions = true;
            EasyLoading.dismiss();
          }
        }
        downloadInfo = info;
      });
    }
  }

  /// 注销账号
  cancelAccount() async {
    bool res = await HttpUtilService.cancelAccount();
    if (res) {
      logOut();
    }
  }

  /// 退出登录
  logOut() async {
    AppConfig.token = '';
    await CacheEncryptionDecryptUtil.removeByKey(key: CacheKeyUtil.token);
    checkLogin();
    if (isRevirew.value) {
      Get.offAllNamed(AppRouters.REVIEW_COMMON_PAGE);
    } else {
      Get.offAllNamed(AppRouters.COMMON_PAGE);
    }
  }

  /// 一键回收
  seckillRecovery () async {
    bool res = await HttpUtilService.seckillRecovery();
    if (res) {
      Get.back();
      EasyLoading.showToast('回收成功');
      checkLogin(loading: false);
    }
  }

  /// 保存分享图
  saveImage(GlobalKey globalKey) async {
    EasyLoading.show();
    RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    var image = await boundary.toImage(pixelRatio: 2.5);
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData!.buffer.asUint8List();
    PermissionStatus status = await Permission.storage.request();
    if (status.isGranted) {
      var result = await ImageGallerySaver.saveImage(pngBytes, quality: 100, name: "shareImage");
      EasyLoading.dismiss();
      if (result['isSuccess']) {
        EasyLoading.showToast('图片保存成功');
        Get.back();
      } else {
        EasyLoading.showToast('图片保存失败');
      }
    } else {
      EasyLoading.dismiss();
      EasyLoading.showToast('请授权权限');
    }
  }

  /// 打开微信客服
  openWeChatCustomerServiceChat() async {
    await fluwx.registerWxApi(
      appId: AppConfig.wxAppId,
      universalLink: AppConfig.universalLink
    );
    if (!await fluwx.isWeChatInstalled) {
      EasyLoading.showToast('请先安装微信');
      return;
    }
    fluwx.openWeChatCustomerServiceChat(
      url: AppConfig.wxCustomerServiceUrl, 
      corpId: AppConfig.corpId
    );
  }

  /// 分享到微信
  shareToWeChar() async {
    await fluwx.registerWxApi(appId: AppConfig.wxAppId, universalLink: AppConfig.universalLink);
    if (!await fluwx.isWeChatInstalled) {
      EasyLoading.showToast('请安装微信');
      return;
    }
    fluwx.shareToWeChat(fluwx.WeChatShareWebPageModel(
      AppConfig.shareWebPage,
      title: '魔法星选',
      thumbnail: fluwx.WeChatImage.asset('assets/icons/icon_logo.png'),
      description: '诚邀您加入魔法星选',
      scene: fluwx.WeChatScene.SESSION
    ));
  }

  /// 分享到QQ
  shareToQQ() async {
    await Tencent.instance.registerApp(appId: AppConfig.qqAppId);
    if (!await Tencent.instance.isQQInstalled()) {
      EasyLoading.showToast('请安装QQ');
      return;
    }
    await Tencent.instance.shareWebpage(
      scene: TencentScene.SCENE_QQ, 
      title: '魔法星选', 
      targetUrl: AppConfig.shareWebPage,
      appName: '魔法星选',
      summary: '诚邀您加入魔法星选',
    );
  }

  /// 首次打开应用时，展示公告
  showNoticeDialog() async {
    AnnouncementsVo? announcementsVo = await HttpUtilService.getAnnouncements(loading: false);
    if (announcementsVo != null) {
      if (announcementsVo.data!.activityId! > 0) {
        DateTime dateTime= DateTime.now();
        int thisDay = dateTime.day;
        int activityDialogDay = await CacheEncryptionDecryptUtil.getIntegerCacheEncryption(key: CacheKeyUtil.activityDialogDay, defaultValue: 0);
        if (versionData.value.isSign == 1 && thisDay != activityDialogDay) {
          CacheEncryptionDecryptUtil.saveIntegerCacheEncryption(key: CacheKeyUtil.activityDialogDay, value: thisDay);
          // 入队
          DialogQueueManager.enqueue(() {
            Get.dialog(ActivityDialog(
              title: '${announcementsVo.data!.title}', 
              description: '${announcementsVo.data!.description}'
            ));
          });
        }
        return;
      }
      // await CacheEncryptionDecryptUtil.removeByKey(key: CacheKeyUtil.noticeArr);
      List<String> _noticeArr = await CacheEncryptionDecryptUtil.getStringArrCacheEncryption(key: CacheKeyUtil.noticeArr, defaultValue: []);
      if (!_noticeArr.contains('${announcementsVo.data!.id}')) {
        _noticeArr.add('${announcementsVo.data!.id}');
        await CacheEncryptionDecryptUtil.saveStringArrCacheEncryption(key: CacheKeyUtil.noticeArr, value: _noticeArr);
        Get.dialog(
          NoticeDialog(
            title: '${announcementsVo.data!.title}',
            description: '${announcementsVo.data!.description}',
          ),
          barrierDismissible: false
        );
      }
    }
  }

  /// 检查摄像头权限
  Future<bool> checkCameraPermission() async {
    // //获取当前的权限
    var status = await Permission.camera.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.camera.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        EasyLoading.showToast('请开启摄像权限');
        return false;
      }
    }
  }

  /// 扫码
  startScan() async {
    if (!await checkCameraPermission()) {
      return;
    }
    ScanBean scanBean = await FlutterHmsScan.loadScanKit();
    if (TextUtil.isEmpty(scanBean.codeResult)) {
      return;
    }
    Uri u = Uri.parse(scanBean.codeResult!);
    if (!u.queryParameters.containsKey('voucherCode')) {
      EasyLoading.showToast('参数异常');
      return;
    } 
    Get.toNamed(
      '${AppRouters.COMMON_PAGE}${AppRouters.WRITE_OFF_PAGE}',
      arguments: {
        'code': u.queryParameters['voucherCode']!
      }
    );
  }
}